package com.liuanbang.saro.sarodemo.base;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.liuanbang.saro.sarodemo.adapter.viewholder.CommentViewHolder;

import java.util.List;

/**
 * 通用RecycleView适配器
 * <p/>
 * 修改:刘安邦 增加监听器 2016/8/24
 * 1.使用点击监听,请使用三参构造
 * 2.VIewHolder单独分离出去,写成了通用ViewHolder,使用方法详见DemoRecycleViewAdapter
 */
public abstract class AbstractRecyclerViewAdapter<T> extends RecyclerView.Adapter<CommentViewHolder> {

    protected int templateViewId;
    protected List<T> operationList;
    private RecyclerView recyclerView;
    private OnRecycleViewItemClickListener onRecycleViewItemClickListener = null;

    //三参数构造方法，需要数据集合,对应的模板ID,对应的RecycleView 若要使用点击事件,则请复写三个参数构造方法
    public AbstractRecyclerViewAdapter(List<T> operationList, int templateViewId, RecyclerView recyclerView) {
        this.templateViewId = templateViewId;
        this.operationList = operationList;
        this.recyclerView = recyclerView;
    }

    //构建模板
    @Override
    public CommentViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(this.templateViewId, parent, false);
        //设置RecycleView的监听事件
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (recyclerView != null) {
                    onRecycleViewItemClickListener.onItemClick(recyclerView.getChildAdapterPosition(view));
                }
            }
        });
        return new CommentViewHolder(view);
    }

    //填充模板
    @Override
    public void onBindViewHolder(CommentViewHolder holder, int position) {
        // ReflectUtil.fillView(holder.itemView, operationList.get(position));
        convert(holder, operationList.get(position));
    }

    //获得数据集合条数
    @Override
    public int getItemCount() {
        return operationList != null ? operationList.size() : 0;
    }

    /**
     * 自定义监听器接口
     */
    public interface OnRecycleViewItemClickListener {
        void onItemClick(int position);
    }

    /**
     * 自定义监听器的set方法
     * 实现RecycleView的监听,直接调用该方法 即可
     *
     * @param listener
     */
    public void setOnRecycleViewItemClickListener(OnRecycleViewItemClickListener listener) {
        onRecycleViewItemClickListener = listener;
    }

    /**
     * 留给调用者去实现,作用是替代ViewHolder
     *
     * @param holder
     * @param t
     */
    public abstract void convert(CommentViewHolder holder, T t);
}
